package com.zk.lettcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 无重复字符的最长子串
 * 滑动窗口
 * 控制左节点，如果出现重复则从该重复的下一个开始
 * @Author: zhang kai
 * @Date: 2021/11/08
 * @Description: https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 */
public class Practice3 {

    public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) {
            return s.length();
        }
        int maxLen = 0;
        int left = 0;//左节点
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                //因为坐标从0开始
                left = Math.max(left, map.get(s.charAt(i)) + 1);
            }
            //更新重复数据的位置
            map.put(s.charAt(i), i);
            maxLen = Math.max(maxLen, i - left + 1 );

        }
        return maxLen;
    }
}
